<template>
  <div class="system-settings-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统配置</span>
        </div>
      </template>
      
      <!-- 配置标签页 -->
      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- 基础配置 -->
        <el-tab-pane label="基础配置" name="basic">
          <el-form :model="basicSettings" :rules="basicSettingsRules" ref="basicSettingsRef" label-width="150px" class="settings-form">
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="basicSettings.systemName" placeholder="请输入系统名称"></el-input>
            </el-form-item>
            <el-form-item label="系统Logo" prop="systemLogo">
              <div class="logo-uploader">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  action=""
                  :auto-upload="false"
                  :on-change="handleLogoChange"
                >
                  <img v-if="basicSettings.systemLogo" :src="basicSettings.systemLogo" class="avatar">
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-button size="small" type="text" @click="handleRemoveLogo">删除</el-button>
              </div>
            </el-form-item>
            <el-form-item label="版权信息" prop="copyright">
              <el-input v-model="basicSettings.copyright" placeholder="请输入版权信息"></el-input>
            </el-form-item>
            <el-form-item label="备案号" prop="icpNumber">
              <el-input v-model="basicSettings.icpNumber" placeholder="请输入网站备案号"></el-input>
            </el-form-item>
            <el-form-item label="客服电话" prop="servicePhone">
              <el-input v-model="basicSettings.servicePhone" placeholder="请输入客服电话"></el-input>
            </el-form-item>
            <el-form-item label="客服邮箱" prop="serviceEmail">
              <el-input v-model="basicSettings.serviceEmail" placeholder="请输入客服邮箱"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveBasicSettings">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 安全配置 -->
        <el-tab-pane label="安全配置" name="security">
          <el-form :model="securitySettings" :rules="securitySettingsRules" ref="securitySettingsRef" label-width="150px" class="settings-form">
            <el-form-item label="登录失败次数限制" prop="loginFailLimit">
              <el-input-number v-model="securitySettings.loginFailLimit" :min="1" :max="20" :step="1"></el-input-number>
              <div class="form-tip">达到此次数后账号将被锁定</div>
            </el-form-item>
            <el-form-item label="账号锁定时长（分钟）" prop="accountLockTime">
              <el-input-number v-model="securitySettings.accountLockTime" :min="5" :max="1440" :step="5"></el-input-number>
            </el-form-item>
            <el-form-item label="密码强度要求">
              <el-checkbox-group v-model="securitySettings.passwordStrength">
                <el-checkbox label="包含大写字母">包含大写字母</el-checkbox>
                <el-checkbox label="包含小写字母">包含小写字母</el-checkbox>
                <el-checkbox label="包含数字">包含数字</el-checkbox>
                <el-checkbox label="包含特殊字符">包含特殊字符</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="密码最小长度" prop="passwordMinLength">
              <el-input-number v-model="securitySettings.passwordMinLength" :min="6" :max="20" :step="1"></el-input-number>
            </el-form-item>
            <el-form-item label="密码过期时间（天）" prop="passwordExpireDays">
              <el-input-number v-model="securitySettings.passwordExpireDays" :min="0" :max="365" :step="1"></el-input-number>
              <div class="form-tip">0表示永不过期</div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveSecuritySettings">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- API配置 -->
        <el-tab-pane label="API配置" name="api">
          <el-form :model="apiSettings" :rules="apiSettingsRules" ref="apiSettingsRef" label-width="150px" class="settings-form">
            <el-form-item label="API请求超时（毫秒）" prop="apiTimeout">
              <el-input-number v-model="apiSettings.apiTimeout" :min="1000" :max="30000" :step="500"></el-input-number>
            </el-form-item>
            <el-form-item label="最大请求频率（次/分钟）" prop="maxRequestRate">
              <el-input-number v-model="apiSettings.maxRequestRate" :min="10" :max="1000" :step="10"></el-input-number>
            </el-form-item>
            <el-form-item label="是否启用缓存" prop="enableCache">
              <el-switch v-model="apiSettings.enableCache"></el-switch>
            </el-form-item>
            <el-form-item v-if="apiSettings.enableCache" label="缓存有效期（秒）" prop="cacheExpireTime">
              <el-input-number v-model="apiSettings.cacheExpireTime" :min="5" :max="3600" :step="5"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveApiSettings">保存配置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 邮件配置 -->
        <el-tab-pane label="邮件配置" name="email">
          <el-form :model="emailSettings" :rules="emailSettingsRules" ref="emailSettingsRef" label-width="150px" class="settings-form">
            <el-form-item label="SMTP服务器地址" prop="smtpServer">
              <el-input v-model="emailSettings.smtpServer" placeholder="请输入SMTP服务器地址"></el-input>
            </el-form-item>
            <el-form-item label="SMTP服务器端口" prop="smtpPort">
              <el-input-number v-model="emailSettings.smtpPort" :min="1" :max="65535" :step="1"></el-input-number>
            </el-form-item>
            <el-form-item label="邮箱账号" prop="emailAccount">
              <el-input v-model="emailSettings.emailAccount" placeholder="请输入邮箱账号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱密码" prop="emailPassword">
              <el-input v-model="emailSettings.emailPassword" type="password" placeholder="请输入邮箱密码"></el-input>
            </el-form-item>
            <el-form-item label="发件人名称" prop="senderName">
              <el-input v-model="emailSettings.senderName" placeholder="请输入发件人名称"></el-input>
            </el-form-item>
            <el-form-item label="是否使用SSL" prop="useSsl">
              <el-switch v-model="emailSettings.useSsl"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveEmailSettings">保存配置</el-button>
              <el-button @click="handleTestEmail">测试发送</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

// 激活的标签页
const activeTab = ref('basic')

// 表单引用
const basicSettingsRef = ref()
const securitySettingsRef = ref()
const apiSettingsRef = ref()
const emailSettingsRef = ref()

// 基础配置
const basicSettings = reactive({
  systemName: '健康管理系统',
  systemLogo: 'https://picsum.photos/200/80?random=10',
  copyright: '© 2023 健康管理系统. 保留所有权利.',
  icpNumber: '粤ICP备12345678号',
  servicePhone: '400-123-4567',
  serviceEmail: 'service@healthsystem.com'
})

// 基础配置验证规则
const basicSettingsRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '系统名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  copyright: [
    { required: true, message: '请输入版权信息', trigger: 'blur' },
    { min: 5, max: 200, message: '版权信息长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  icpNumber: [
    { required: true, message: '请输入备案号', trigger: 'blur' }
  ],
  servicePhone: [
    { pattern: /^1[3-9]\d{9}$|^400-\d{3}-\d{4}$/, message: '请输入有效的客服电话', trigger: 'blur' }
  ],
  serviceEmail: [
    { type: 'email', message: '请输入有效的客服邮箱', trigger: 'blur' }
  ]
}

// 安全配置
const securitySettings = reactive({
  loginFailLimit: 5,
  accountLockTime: 30,
  passwordStrength: ['包含小写字母', '包含数字'],
  passwordMinLength: 8,
  passwordExpireDays: 90
})

// 安全配置验证规则
const securitySettingsRules = {
  loginFailLimit: [
    { required: true, message: '请设置登录失败次数限制', trigger: 'blur' }
  ],
  accountLockTime: [
    { required: true, message: '请设置账号锁定时长', trigger: 'blur' }
  ],
  passwordMinLength: [
    { required: true, message: '请设置密码最小长度', trigger: 'blur' }
  ],
  passwordExpireDays: [
    { required: true, message: '请设置密码过期时间', trigger: 'blur' }
  ]
}

// API配置
const apiSettings = reactive({
  apiTimeout: 10000,
  maxRequestRate: 100,
  enableCache: true,
  cacheExpireTime: 60
})

// API配置验证规则
const apiSettingsRules = {
  apiTimeout: [
    { required: true, message: '请设置API请求超时时间', trigger: 'blur' }
  ],
  maxRequestRate: [
    { required: true, message: '请设置最大请求频率', trigger: 'blur' }
  ],
  cacheExpireTime: [
    { required: () => apiSettings.enableCache, message: '请设置缓存有效期', trigger: 'blur' }
  ]
}

// 邮件配置
const emailSettings = reactive({
  smtpServer: 'smtp.example.com',
  smtpPort: 465,
  emailAccount: 'noreply@example.com',
  emailPassword: '',
  senderName: '健康管理系统',
  useSsl: true
})

// 邮件配置验证规则
const emailSettingsRules = {
  smtpServer: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP服务器端口', trigger: 'blur' }
  ],
  emailAccount: [
    { required: true, message: '请输入邮箱账号', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱账号', trigger: 'blur' }
  ],
  emailPassword: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ],
  senderName: [
    { required: true, message: '请输入发件人名称', trigger: 'blur' }
  ]
}

// 处理Logo上传
const handleLogoChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    basicSettings.systemLogo = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 移除Logo
const handleRemoveLogo = () => {
  ElMessageBox.confirm('确定要删除当前Logo吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    basicSettings.systemLogo = ''
    ElMessage.success('Logo已删除')
  })
}

// 保存基础配置
const handleSaveBasicSettings = () => {
  basicSettingsRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存配置
      ElMessage.success('基础配置保存成功')
    }
  })
}

// 保存安全配置
const handleSaveSecuritySettings = () => {
  securitySettingsRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存配置
      ElMessage.success('安全配置保存成功')
    }
  })
}

// 保存API配置
const handleSaveApiSettings = () => {
  apiSettingsRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存配置
      ElMessage.success('API配置保存成功')
    }
  })
}

// 保存邮件配置
const handleSaveEmailSettings = () => {
  emailSettingsRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存配置
      ElMessage.success('邮件配置保存成功')
    }
  })
}

// 测试发送邮件
const handleTestEmail = () => {
  ElMessageBox.prompt('请输入接收测试邮件的邮箱地址', '测试邮件', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
    inputErrorMessage: '邮箱格式不正确'
  }).then(({ value }) => {
    // 实际项目中应该调用API发送测试邮件
    ElMessage.success(`测试邮件已发送至 ${value}`)
  })
}
</script>

<style scoped>
.system-settings-container {
  padding: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.settings-tabs {
  margin-top: 20px;
}

.settings-form {
  margin-top: 20px;
}

.form-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.logo-uploader {
  display: flex;
  align-items: center;
  gap: 15px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 200px;
  height: 80px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 200px;
  height: 80px;
  display: block;
  object-fit: contain;
}
</style>